package cn.ivicar.oss.quartz;

import cn.com.carsmart.ws.ibatis.model.BaseExample;
import cn.com.carsmart.ws.model.TotalStatistic;
import cn.com.carsmart.ws.model.Vehicle;
import cn.com.carsmart.ws.model.VehicleState;
import cn.com.carsmart.ws.service.TotalStatisticManager;
import cn.com.carsmart.ws.service.VehicleManager;
import cn.com.carsmart.ws.service.VehicleStateManager;
import cn.ivicar.oss.guice.OssGuiceConfig;
import cn.ivicar.redis.JedisClusterFactory;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.JedisCluster;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * 将设备位置信息、最近上线时间、更新时间存入数据库
 */
public class VehicleStatJob implements Job {

    private static transient final Logger LOGGER = LoggerFactory.getLogger(VehicleStatJob.class);

    private static final String IOV_SHADOW_GPS = "iov:shadow:gps:";
    private static final String IOV_ONLINE = "iov:online:";

    private static VehicleStateManager vehicleStateManager =
        OssGuiceConfig.getStaticInjector().getInstance(VehicleStateManager.class);
    private static VehicleManager vehicleManager =
        OssGuiceConfig.getStaticInjector().getInstance(VehicleManager.class);

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        LOGGER.info(String.format("定时任务：VehicleStatJob开始执行,开始时间： %s=", sdf.format(new Date())));
        List<Vehicle> list = this.vehicleManager.list();
        if (list != null && list.size() > 0) {
            JedisCluster cluster = JedisClusterFactory.getDefaultJedisCluster();
            for (Vehicle vehicle : list) {
                String serial = vehicle.getSerial();
                String shadowStr = cluster.get(IOV_SHADOW_GPS + serial);
                if (StringUtils.isNotBlank(shadowStr)) {
                    String isOnline = cluster.get(IOV_ONLINE + serial);

                    JSONObject shadow = JSONObject.fromObject(shadowStr);
                    //
                    String lat = shadow.optString("amapLat", null);
                    String lng = shadow.optString("amapLng", null);
                    long time = shadow.optLong("time", 0);
                    VehicleState vehicleState = new VehicleState();
                    vehicleState.setVehicleId(vehicle.getId());
                    vehicleState.setLongitude(Double.valueOf(lng));
                    vehicleState.setLatitude(Double.valueOf(lat));
                    vehicleState.setLastReportTime(new Date(time));
                    vehicleState.setUpdated(new Date());

                    if (StringUtils.isNotBlank(isOnline)) {
                        vehicleState.setOnline(true);
                    } else {
                        vehicleState.setOnline(false);
                    }

                    BaseExample example = this.vehicleStateManager.getExample();
                    example.or().andPropertyEqualTo(vehicle.getId(), "vehicleId");
                    List<VehicleState> vehicleStates =
                        this.vehicleStateManager.listByBaseExample(example);
                    if (vehicleStates != null && vehicleStates.size() > 0) {
                        this.vehicleStateManager.updateSelective(vehicleState);
                    } else {
                        this.vehicleStateManager.insert(vehicleState);
                    }

                }

            }
        }
        LOGGER.info(String.format("定时任务：VehicleStatJob执行完毕！结束时间： %s", sdf.format(new Date())));
    }
}
